package com.neuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class ChatRoom implements Runnable {
	// 当前连接的客户端
	private Socket socket = null;
	// 所有的连接客户端
	private Map<String, Socket> clientMap = new Hashtable<String, Socket>();

	public ChatRoom(Socket socket, Map<String, Socket> clientMap) {
		this.socket = socket;
		this.clientMap = clientMap;
	}

	@Override
	public void run() {
		while (true) {
			InputStream inputStream = null;
			OutputStream outputStream = null;
			
			try {
				inputStream = socket.getInputStream();
				byte[] b = new byte[512];
				int len = inputStream.read(b);
				String words=new String(b, 0, len).trim();
				if("quit".equalsIgnoreCase(words)) {
					break;
				}

				//把内容转发到其他客户端
				Set<String> keySet = clientMap.keySet();
				Iterator<String> iterator = keySet.iterator();
				 
				Socket socket = null;
				String client=null;
				while (iterator.hasNext()) {
					String clientip = iterator.next();
					try {
						socket = clientMap.get(clientip);
						if (clientip != socket.getInetAddress().getHostAddress()) {
							client=socket.getInetAddress().getHostAddress();
							outputStream = socket.getOutputStream();
							String reply=socket.getInetAddress().getHostAddress()+":"+words;
							outputStream.write(reply.getBytes());
						}
					} catch (IOException e) {
						if(socket==null || socket.isClosed()) {
							clientMap.remove(client);
						}
					}
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
